import { createRouter, createWebHistory } from 'vue-router';
import { nextTick } from 'vue';
import { useTabStore } from '@/stores/tabStore';
import home from '@/pages/home/index.vue';
import doctor from '@/pages/DoctorManagement/index.vue';
import elderly from '@/pages/elderly/list.vue';
import health from '@/pages/HealthManagement/HealthRecords.vue';
import patientInfo from '@/pages/PatientManagement/PatientInfo.vue';
import patientList from '@/pages/PatientManagement/PatientList.vue';
import patientArchives from '@/pages/PatientManagement/PatientArchives.vue';
import patientFollowup from '@/pages/PatientManagement/PatientFollowup.vue';
import login from '@/pages/Login/Index.vue';
import onlineConsultation from '@/pages/ConsultingServiceManagement/OnlineConsultation.vue';
import telephoneConsultation from '@/pages/ConsultingServiceManagement/TelephoneConsultation.vue';
import intelligentCustomerService from '@/pages/ConsultingServiceManagement/IntelligentCustomerService.vue';
import callRecords from '@/pages/ConsultingServiceManagement/CallRecords.vue';
import patientSegmentation from '@/pages/DiseaseSourceManagement/PatientSegmentation.vue';
import memberManagement from '@/pages/DiseaseSourceManagement/MemberManagement.vue';
import patientRecommend from '@/pages/DiseaseSourceManagement/PatientRecommend.vue';
import reservationRegister from '@/pages/ReservationManagement/ReservationRegister.vue';
import reservationInspectTest from '@/pages/ReservationManagement/ReservationInspectTest.vue';
import reservationReminderChange from '@/pages/ReservationManagement/ResevationReminderChange.vue';
import reservationRecords from '@/pages/ReservationManagement/ReservationRecords.vue';
import patientDataAnalysis from '@/pages/DataAnalysis/PatientDataAnalysis.vue';
import businessDataAnalysis from '@/pages/DataAnalysis/BusinessDataAnalysis.vue';
import marketingEffectAnalysis from '@/pages/DataAnalysis/MarketingEffectAnalysis.vue';
import forgetPassword from '@/pages/Login/ForgetPassword.vue';
import modifyPassword from '@/pages/Login/ModifyPassword.vue';
import reg from '@/pages/Login/Reg.vue';

const routes = [
  {
    path: '/login',
    name: '登录',
    component: login,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/',
    name: '首页',
    component: home,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/doctor/index',
    name: '医生管理',
    component: doctor,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/elderly/list',
    name: '老年人管理',
    component: elderly,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/reservationRegister',
    name: '预约挂号',
    component: reservationRegister,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/reservationInspectTest',
    name: '预约检查与检验',
    component: reservationInspectTest,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/reservationReminderChange',
    name: '预约提醒与变更',
    component: reservationReminderChange,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/reservationRecords',
    name: '预约记录',
    component: reservationRecords,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/health/records',
    name: '健康档案',
    component: health,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/patient/info',
    name: '患者信息',
    component: patientInfo,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/patient/list',
    name: '患者列表',
    component: patientList,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/patient/archives',
    name: '患者档案',
    component: patientArchives,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/patient/followup',
    name: '患者随访',
    component: patientFollowup,
    meta: {
      keepAlive: false,
    },
  },
  {
    path: '/onlineConsultation',
    name: '在线咨询',
    component: onlineConsultation,
  },
  {
    path: '/telephoneConsultation',
    name: '电话咨询',
    component: telephoneConsultation,
  },
  {
    path: '/intelligentCustomerService',
    name: '智能客服',
    component: intelligentCustomerService,
  },
  {
    path: '/callRecords',
    name: '通话记录',
    component: callRecords,
  },
  {
    path: '/patient/segmentation',
    name: '患者细分与精准营销',
    component: patientSegmentation,
  },
  {
    path: '/memberManagement',
    name: '会员管理',
    component: memberManagement,
  },
  {
    path: '/patientRecommend',
    name: '口碑营销与患者推荐',
    component: patientRecommend,
  },
  {
    path: '/patientDataAnalysis',
    name: '患者数据分析',
    component: patientDataAnalysis,
  },
  {
    path: '/businessDataAnalysis',
    name: '业务数据分析',
    component: businessDataAnalysis,
  },
  {
    path: '/marketingEffectAnalysis',
    name: '营销效果分析',
    component: marketingEffectAnalysis,
  },
  {
    path: '/forgetPassword',
    name: '忘记密码',
    component: forgetPassword,
  },
  {
    path: '/modifyPassword',
    name: '修改密码',
    component: modifyPassword,
  },
  {
    path: '/reg',
    name: '注册',
    component: reg,
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

// 路由前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const whiteList = ['/login', '/forgetPassword']; // 白名单路由

  // 处理白名单路由
  if (whiteList.includes(to.path)) {
    return next();
  }

  // 处理未登录状态
  if (!token) {
    return next({ 
      path: '/login',
      replace: true
    });
  }

  try {
    const tabStore = useTabStore();
    // 如果是已打开的页面，确保 keepAlive 为 true
    if (tabStore.tabs.some(tab => tab.index === to.path)) {
      // 修改路由配置中的 meta
      const route = routes.find(route => route.path === to.path);
      if (route) {
        route.meta = { ...route.meta, keepAlive: true };
      }
      // 修改当前路由的 meta
      to.meta = { ...to.meta, keepAlive: true };
    }
  } catch (error) {
    console.error('处理页面缓存状态失败:', error);
  }

  next();
});

// 路由后置守卫
router.afterEach((to) => {
  // 只在非白名单路由下更新标签状态
  const whiteList = ['/login', '/forgetPassword'];
  
  if (!whiteList.includes(to.path) && to.name) {
    nextTick(() => {
      try {
        const tabStore = useTabStore();
        if (to.name && !to.meta?.noTab) {
          tabStore.$patch((state) => {
            // 确保首页标签存在
            if (!state.tabs.find(tab => tab.index === '/')) {
              state.tabs.unshift({
                name: '首页',
                index: '/',
                meta: { keepAlive: true }
              });
            }

            // 如果不是首页，且标签不存在，则添加新标签
            if (to.path !== '/' && !state.tabs.find(tab => tab.index === to.path)) {
              state.tabs.push({
                name: to.name,
                index: to.path,
                meta: { keepAlive: true }
              });
            }

            // 更新当前活动标签
            state.activeTab = to.path;

            // 更新路由配置
            const route = routes.find(route => route.path === to.path);
            if (route) {
              route.meta = { ...route.meta, keepAlive: true };
            }
          });
        }
      } catch (error) {
        console.error('更新标签页失败:', error);
      }
    });
  }
});

export default router;